<template>
  <div class="person-wrap">
    <n-row gutter="12">
      <n-col :span="3" :offset="2">
        <div class="left">
          <n-collapse default-expanded-names="1" accordion>
            <n-collapse-item title="个人资料" name="1">
              <div>信息编辑</div>
            </n-collapse-item>
            <n-collapse-item title="待定" name="2">
              <div>待定</div>
            </n-collapse-item>
          </n-collapse>
        </div>
      </n-col>
      <n-col :span="17" :offset="0">
        <el-tabs
            style="margin-top: 40px;caret-color: #bc4258"
            v-model="activeName"
            @tab-click="handleClick">
          <el-tab-pane label="基本信息" name="3">
              <div class="right">
                  <div style="display:flex; flex-direction: row; width: auto">
                    <div class="item-left">
<!--                      个人昵称-->
                      <div class="row-spacing">
                        <div class="font-spacing"><a>个人昵称：</a><a class="red">*</a></div>
                        <n-input type="text" v-model:value="user.name" autosize style="width: 70%" placeholder="请输入个人昵称 " />
                      </div>
<!--                      身高-->
                      <div class="row-spacing">
                        <div class="font-spacing"><a>身高(cm)：</a><a class="red">*</a></div>
                        <n-input type="number" v-model:value="user.height" autosize style="width: 70%" placeholder=" 请输入身高" />
                      </div>
<!--                      出生日期-->
                      <div class="row-spacing">
                        <div class="font-spacing"><a>出生日期：</a><a class="red">*</a></div>
                        <n-date-picker type="date" v-model:value="user.age" autosize style="width: 70%" placeholder=" 请选择出生日期"/>
                        <!--          <pre>{{ JSON.stringify(timestamp) }}</pre>-->
                      </div>
<!--                      判断是否是学校人员-->
                      <div class="row-spacing">
                        <div class="font-spacing"><a>是否是学校人员：</a><a class="prompt">*</a></div>
                        <n-switch v-model:value="userIsSchool" :rail-style="railStyle1" class="toggle">
                          <template #checked>是</template>
                          <template #unchecked>否</template>
                        </n-switch>
                      </div>
<!--                      学院-->
                      <div class="row-spacing">
                        <div class="font-spacing"><a>学院：</a></div>
                        <!--          判断是否是学校人员，不是禁用/是启用-->
                        <n-select v-model:value="user.collegeId"
                                  :options="collegeOptions"
                                  :disabled="!userIsSchool"
                                  autosize style="width: 70%" placeholder="请选择学院"/>
                      </div>
<!--                       年级-->
                      <div class="row-spacing">
                        <div class="font-spacing"><a>年级：</a></div>
                        <n-select v-model:value="user.grade"
                                  :options="gradeOptions"
                                  :disabled="!userIsSchool"
                                  autosize style="width: 70%" placeholder="请选择年级"/>
                      </div>

                    </div>
                    <div class="item-right">
<!--                      性别-->
                      <div class="row-spacing">
                        <div class="font-spacing"><a>性别：</a><a class="red">*</a></div>
                        <n-switch v-model:value="userSex"  :rail-style="railStyle"  class="toggle">
                          <template #checked>女生</template>
                          <template #unchecked>男生</template>
                        </n-switch>
                      </div>
<!--                      体重-->
                      <div class="row-spacing">
                      <div class="font-spacing"><a>体重(kg)：</a><a class="red">*</a></div>
                      <n-input type="number" v-model:value="user.weight" autosize style="width: 70%" placeholder="请输入体重 " />
                      </div>
<!--                      电话号码-->
                      <div class="row-spacing">
                        <div class="font-spacing"><a>电话号码：</a></div>
                        <n-input type="number" v-model:value="user.phone" autosize style="width: 70%" maxlength="11" placeholder="请输入电话号码"/>
                      </div>
<!--                      微信号-->
                      <div class="row-spacing">
                        <div class="font-spacing"><a>微信号：</a></div>
                        <n-input v-model:value="user.wxNumber" autosize style="width: 70%" placeholder="请输入微信号 " />
                      </div>
<!--                      邮箱-->
                      <div class="row-spacing">
                        <div class="font-spacing"><a>邮箱：</a></div>
                        <n-auto-complete
                            autosize style="width: 70%"
                            v-model:value="emailValue"
                            :input-props="{
                          autocomplete: 'disabled'}"
                            :options="emailOptions"  placeholder="请输入邮箱 "/>
                      </div>
<!--                      提交按钮-->
                      <div class="row-spacing" style="margin-top: 20px">
                        <el-button type="success" color="#bc4258" class="ro" @click="revise" >
                          继续填写
                        </el-button><a class="prompt">标志*为必填项</a>
                      </div>
                    </div>
                  </div>

              </div>
          </el-tab-pane>
          <el-tab-pane label="个人展示" name="4">
              <div class="right">
                <div style="display:flex; flex-direction: row ">
                  <div class="item-left">
                    <div class="font-spacing"><a>个人资料封面展示：</a><a class="red">*</a></div>
                    <el-upload
                        v-model:file-list="fileList"
                        :action="apiBase+apis.uploadImg"
                        :on-change="changeimg1"
                        :class="{hide:hideUpload1}"
                        list-type="picture-card"
                        :auto-upload="true"
                        :on-preview="Preview1"
                        :on-remove="handleRemove1"
                        :on-success="onSuccess1"
                        :before-upload="beforeAvatarUpload"
                        :limit="1">
                      <el-icon><Plus/></el-icon>
                    </el-upload>
                    <el-dialog v-model="imageVisible" >
                      <img :src="imageUrl" style="width: 100%" alt="">
                    </el-dialog>
                  </div>
                  <div class="item-right">
                    <div class="font-spacing"><a>个人介绍：</a><a class="red">*</a></div>
                    <el-input
                        v-model="user.introduction"
                        :rows="6"
                        type="textarea"
                        placeholder="例如：
我的名字叫五到七，我喜欢唱歌，跳舞，打篮球，全民制作人们投我一票吧！"
                    />
                  </div>
                </div>

                <div class="font-spacing"><a>照片墙：</a><a class="red">（限制 6 张）</a></div>
                <el-upload
                      name="file"
                      v-model:file-list="fileList2"
                      :action="apiBase+apis.uploadImg"
                      :on-change="changeimg2"
                      :class="{hide:hideUpload2}"
                      list-type="picture-card"
                      :auto-upload="true"
                      :on-error="onError2"
                      :on-preview="Preview2"
                      :on-remove="handleRemove2"
                      :on-success="onSuccess2"
                      :before-upload="beforeAvatarUpload"
                      :limit="6">
                    <el-icon><Plus /></el-icon>
                  </el-upload>
                <el-dialog v-model="dialogVisible">
                    <img :src="dialogImageUrl" style="width: 100%" alt="">
                  </el-dialog>

                <div class="font-spacing" style="margin-top: 5px"><a>标签展示：</a><a class="red">*</a></div>
                <!--:class="tagsIndex[tagIndex]"-->
                <el-tag
                    v-for="(tag,tagIndex) in LabelTag"
                    :key="tag"
                    class="mx-1"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(tagIndex)"
                >
                  {{ tag.label }}
                </el-tag>
                <el-input
                    v-if="inputVisible"
                    ref="InputRef"
                    v-model="inputValue"
                    class="ml-1 w-20 tags-info"
                    size="large"
                    @keyup.enter="handleInputConfirm"
                    @blur="handleInputConfirm"
                    maxlength="6"
                />
                <el-button v-else class="button-new-tag ml-1" size="small" style="margin-left: 4px" @click="showInput">
                  添加标签
                </el-button>

                <el-button type="success" @click="submitUpload" color="#bc4258" style="margin-left: 140px; font-size: 12px">
                  修改保存
                </el-button><a class="prompt">标志*为必填项</a>


              </div>
          </el-tab-pane>
        </el-tabs>
      </n-col>
    </n-row>
  </div>
</template>

<script>
import {ref, computed, getCurrentInstance} from 'vue'
import { apis,apiBase,ftpUrlImg} from "@/global/config";
import { Plus } from '@element-plus/icons-vue'
import { ElInput,ElMessage, UploadProps, UploadUserFile } from 'element-plus'

export default{
  name: "PersonalData",

  created() {
    //获取标签数据
    this.$requestCenter.defaultListTag().then((res) =>{
        this.LabelTag = res.data
    })
    //获取学院数据
    this.$requestCenter.collegeList().then((res) =>{
      for (let datum of res.data) {
        this.collegeOptions.push({label:datum.collegeName,value:datum.id})
      }
      console.log(this.collegeOptions)
    })
      //获取用户信息
    this.$requestCenter.getUserInfo().then((e)=>{
        console.log(e)
        if(e.data.user.isComplete == 1){
            this.user = e.data.user
            this.emailValue =  e.data.user.email;
            this.LabelTag = e.data.labelList
            if (e.data.user.isSchool == 1){
                this.userIsSchool = true
            }else {
                this.userIsSchool = false
            }
            if(e.data.user.sex == 1){
                this.userSex = false
            }else {
                this.userSex = true
            }
            if(e.data.user.coverPictureUrl != null && e.data.user.coverPictureUrl != "" &&  e.data.user.coverPictureUrl != "-1"){
                this.fileList =[
                    {
                        name: e.data.user.coverPictureUrl,
                        url: ftpUrlImg + e.data.user.coverPictureUrl
                    }
                ]
                this.hideUpload1=true
            }
            if (e.data.bannerLists!=null){
                for (let bannerList of e.data.bannerLists) {
                    let img = {
                        name: bannerList.bannerImgUrl,
                        url: ftpUrlImg + bannerList.bannerImgUrl
                    }
                    this.fileList2.push(img)
                }
                if (e.data.bannerLists.length >= this.limitCount2){
                    this.hideUpload2=true
                }
            }
          //   this.imageUrl = ftpUrlImg + data.data.user.coverPictureUrl
        }else {
          this.user.name = e.data.user.name
          if(e.data.user.sex == 1){
            this.userSex = false
          }else {
            this.userSex = true
          }
        }
    })
  },
  methods:{
    handleClick(tab,event){
      console.log(tab,event);
    },
      //上传图片成功
    onError1(){
      this.$message("上传图片失败！")
    },
      //上传图片失败
    onError2(){
        this.$message("上传图片失败！")
    },
    onSuccess1(response,uploadFile,uploadFiles){
      // console.log(uploadFiles[0].response.data)
        this.user.coverPictureUrl = uploadFiles[0].response.data
      // console.log(response,uploadFile,uploadFiles)
    },
    onSuccess2(response,uploadFile,uploadFiles){
        // for (let i = 0; i < uploadFiles.length; i++) {
        //     this.userBannerList[i] = uploadFiles[i].response.data
        // }
        this.userBannerList = uploadFiles
      // console.log(response,uploadFile,uploadFiles)
        console.log(this.userBannerList)
    },
    //删除图片
    handleRemove1(file, fileList) {
      console.log(file, fileList);
      if (file.response){
          this.$requestCenter.removeImg(file.response.data)
      }
      this.user.coverPictureUrl = "-1"
      this.deleteImgName = file.name;
      this.hideUpload1 = fileList.length >= this.limitCount1;
        console.log(this.user);
    },
    handleRemove2(file, fileList) {
      console.log(file, fileList);
        if (file.response){
            this.$requestCenter.removeImg(file.response.data)
        }
      this.userBannerList = fileList
      console.log(this.userBannerList)
      this.hideUpload2 = fileList.length >= this.limitCount2;
    },
    //预览图片
    Preview1(file){
      this.imageUrl = file.url;
      this.imageVisible = true;
    },
    Preview2(file) {
        console.log(file)
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //图片限制不显示按钮
    changeimg1(file,fileList){
        // console.log(fileList)
      this.hideUpload1 = fileList.length >= this.limitCount1;
    },
    changeimg2(file,fileList){
        // console.log(fileList)
      this.hideUpload2 = fileList.length >= this.limitCount2;
    },
    //判断大小格式
    beforeAvatarUpload(file) {
      console.log(file)
      // const isJPG = file.type === '/jpeg';
      // const isPNG = file.type === 'image/png';
      const isImg = file.type.search("image")!= -1;
      // console.log(isImg)
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isImg) {
        this.$message.error('您上传的不是图片！');
        return isImg;
      }else if (!isLt5M){
        this.$message.error('您上传图片的大小不能超过 5MB!');
        return isLt5M;
      }
    },
    //tag输入框获取焦点
    handleInputConfirm(){
      let isCf = true;
      if (this.inputValue==""){
        isCf=false
      }
      for (let label of this.LabelTag) {
        console.log(label.label)
        if (label.label==this.inputValue){
          this.open1("标签重复！","warning")
          isCf=false;
          break
        }
      }
      if (isCf){
        this.LabelTag.push({label: this.inputValue})
        // this.inputVisible=false;
        // this.inputValue=""
        // isCf=false;
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    // 判断用户年龄
    getAge(Timestamp){
      let birthdays = new Date(Timestamp)
      let d = new Date();
      let age =
          d.getFullYear() -
          birthdays.getFullYear() -
          (d.getMonth() < birthdays.getMonth() ||
          (d.getMonth() == birthdays.getMonth() &&
              d.getDate() < birthdays.getDate())
              ? 1
              : 0);
      return age;
    },
    //基本信息修改保存跳转
    revise(){
      if (this.getAge(this.user.age)<15||this.getAge(this.user.age)>60){
          this.$message.warning("您输入的年龄似乎不太真实！")
          return;
      }
      if (this.user.phone!=null){
          let phoneReg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
          if (!phoneReg.test(this.user.phone)){
              this.$message.warning("请输入正确的手机号！");
              return;
          }
      }
      this.user.email = this.emailValue;
      if (this.user.name == null||this.user.height == null||
          this.user.weight == null||this.user.age == null){
        this.$message.warning('还有未填完的必填项')
        // this.open1("还有未填完的必填项","warning")
      }else if (this.userIsSchool && this.user.collegeId==null){
          this.$message.warning(' 请选择学院！')
      }else if (this.userIsSchool && this.user.grade==null){
        this.$message.warning(' 请选择年级！')
      }
      else {
        this.$message.success('保存成功')
        console.log(this.user)
        this.activeName = 4 + "";
      }
    },
    //个人展示信息修改保存
    submitUpload(){
      if (this.getAge(this.user.age)<15||this.getAge(this.user.age)>60){
          this.$message.warning("您输入的年龄似乎不太真实！")
          return;
      }
        if (this.user.phone!=null){
            let phoneReg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
            if (!phoneReg.test(this.user.phone)){
                this.$message.warning("请输入正确的手机号！")
                return;
            }
        }
      if (this.user.name == null||this.user.height == null||
          this.user.weight == null||this.user.age == null){
        this.$message.warning('基本信息还有未填完的必填项')
        // this.open1("还有未填完的必填项","warning")
      }else if (this.userIsSchool && this.user.collegeId==null){
        this.$message.warning(' 基本信息还有学院请选择！')
      }else if (this.userIsSchool && this.user.grade==null){
        this.$message.warning(' 基本信息还有年级请选择！！')
      }
      // else if (){
      //
      // }
      else {
        if (this.user.coverPictureUrl == "-1") {
          console.log(this.user.coverPictureUrl)
          this.$requestCenter.removeImg(this.deleteImgName)
        }
        if (this.userSex) {
          this.user.sex = 1
        } else {
          this.user.sex = 2
        }
        if (!this.userSex) {
          this.user.sex = 1
        } else {
          this.user.sex = 2
        }
        if (!this.userIsSchool) {
          this.user.isSchool = 0;
          this.user.collegeId = null;
          this.user.grade = null;
        } else {
          this.user.isSchool = 1;
        }

        console.log("this.userBannerList", this.userBannerList)
        let bannerList = [];
        for (let i = 0; i < this.userBannerList.length; i++) {
          if (this.userBannerList[i].response) {
            bannerList[i] = this.userBannerList[i].response.data
          } else {
            bannerList[i] = this.userBannerList[i].name
          }
        }
        console.log("用户提交信息")
        console.log(this.user)
        console.log(bannerList)
        console.log(this.LabelTag);

        this.$requestCenter.userInfo({user: this.user, labelList: this.LabelTag, bannerList: bannerList}).then((e) => {
          console.log(e)
          if (e.code == 20031) {
            this.$message.success("保存成功！")
              //刷新资料完整状态
              this.$requestCenter.checkWebToken().then((e) => {
                  if (e.data != null) {
                      this.isComplete = e.data.isComplete
                  }
              })
          } else {
            this.$message.error("保存失败！")
          }
        })
      }

    },
    //添加标签
    showInput(){
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.InputRef.$refs.input.focus();
      });
    },
    //删除标签
    handleClose(tag){
      this.LabelTag.splice(tag, 1)
    },
  },
  setup () {
      const isComplete = getCurrentInstance().appContext.config.globalProperties.$isComplete
    //消息弹出
    const open1 = (message,type) => {
      ElMessage({
        message: message,
        type: type,
      })
    }
    //定义邮箱下拉
    const valueRef = ref("");

    return {
        isComplete,
      //列表
      fileList:ref([]),
      fileList2:ref([]),
      //删除的封面图名
      deleteImgName:ref(),
      //上传图片
      apis,
      apiBase,
      //标签页默认
      activeName:ref("3"),
      //个人封面
      imageUrl:ref(""),
      imageVisible:ref(false),
      //照片墙
      dialogImageUrl:ref(""),
      dialogVisible:ref(false),
      //限制一张即隐藏添加按钮
      limitCount1:ref(1),
      hideUpload1:ref(false),
      limitCount2:ref(6),
      hideUpload2:ref(false),
      // //个人介绍
      // textarea:ref(""),
      //添加标签
      inputValue:ref(''),
      inputVisible:ref(false),
      open1,
      //性别值
      userSex:ref(false),
      //是否学校
      userIsSchool:ref(false),
      //出生日期
      Timestamp:ref(null),
      //提交时的数据
      user:ref({
        name:null,
        sex:1,
        height:null,
        weight:null,
        age:null,
        phone:null,
        email:null,
        wxNumber:null,
        isSchool:0,
        collegeId:null,
        grade:null,
        coverPictureUrl:null,
        introduction:null,
      }),
      //标签列表
      LabelTag:ref([]),
      //用户多图
      userBannerList:ref([]),
      //邮箱下拉框
      emailValue: valueRef,
      emailOptions: computed(() => {
        return ["@qq.com", "@gmail.com", "@163.com" ].map((suffix) => {
          const prefix = valueRef.value.split("@")[0];
          return {
            label: prefix + suffix,
            value: prefix + suffix
          };
        });
      }),
      //学院下拉框
      collegeOptions: ref([]),
      //年级下拉框
      gradeOptions:ref([
        {
          label: "大一",
          value: "1"
        },
        {
          label: "大二",
          value: "2"
        },
        {
          label: "大三",
          value: "3",
        },
        {
          label: "大四",
          value: "4"
        },
      ]),
      //性别选择颜色
      railStyle: ({focused, checked}) => {
        const style = {};
        if (checked) {
          style.background = "#bc4258";
          if (focused) {
            style.boxShadow = "0 0 0 2px #d0305040";
          }
        } else {
          style.background = "#2486b9";
          if (focused) {
            style.boxShadow = "0 0 0 2px #2080f040";
          }
        }
        return style;
      },
      //是否是学校人员
      railStyle1:({focused, checked}) => {
        const style = {};
        if (checked) {
          style.background = "#bc4258";
          if (focused) {
            style.boxShadow = "0 0 0 2px #d0305040";
          }
        } else {
          style.background = "#5cb3cc";
          if (focused) {
            style.boxShadow = "0 0 0 2px #2080f040";
          }
        }
        return style;
      },
      //禁用初始顺序
      disabled: ref(false),
      tagsIndex:[
          'color1','color2','color3','color4','color5','color6'
      ]
    }
  }
}
</script>

<style scoped>

/*字行距*/
.font-spacing{
  padding-top: 10px;
  padding-bottom: 10px;
}
/*块行距*/
.row-spacing{
  padding-top: 10px;
  padding-bottom: 10px;
}
/*切换按钮*/
.toggle{
  padding-top: 16px;
  padding-bottom: 18px;
}
.item-left{
  width: 500px;
}
.item-right{
  width: 500px;

}
.person-wrap{
  padding-top: 60px;
  padding-bottom: 20px;
}
.left{
  padding-top: 50px;
  padding-bottom: 50px;
  font-size: 12px;
}
.right{

  padding-bottom: 50px;
  font-size: 12px;
}
/*行级排序*/
.ro{
  margin-top: 7px;
  margin-bottom: 7px;
  font-size: 12px;
}
/*警示字*/
.prompt{
  margin-left: 10px;
  font-size: 2px;
  color: red;
  text-decoration:none;
}
.red{
  color: red;
  text-decoration:none;
}
/*标签输入框*/
.tags-info{
  max-width: 70px;
  height: 25px;
  line-height: 25px;
  border: 1px solid #7aa1d2;
  border-radius: 4px;
  background: #7aa1d2;
  color: #409EFF;
  outline: #7aa1d2;
  font-size: 12px;
  margin-left: 5px;
}
/*添加图片到上限隐藏添加按钮
">>>"穿透scoped来实现样式*/
.hide >>>.el-upload--picture-card {
  display: none;
}
>>>.el-tabs__nav .el-tabs__item{
  color: #333;
}
>>>.el-tabs__active-bar{
  border: 1px solid #f0c9cf;
}
.el-input__inner::placeholder{
  color: #aab2bd;
  /* placeholder字体大小 */
  font-size: 14px;
  letter-spacing: 1px;
}
/*.color1{*/
/*  background: #f1939c;*/
/*  color: #fff;*/
/*}*/
/*.color2{*/
/*  background: #d276a3;*/
/*  color: #fff;*/
/*}*/
/*.color3{*/
/*  background: #f0c9cf;*/
/*  color: #fff;*/
/*}*/
/*.color4{*/
/*  background: #e16c96;*/
/*  color: #fff;*/
/*}*/
/*.color5{*/
/*  background: #d1c2d3;*/
/*  color: #fff;*/
/*}.color6{*/
/*   background: #ef82a0;*/
/*   color: #fff;*/
/* }*/

</style>